package com.mworld.galaxy.bull.service.product;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import com.mworld.galaxy.bull.entity.product.Shop;
import com.mworld.galaxy.bull.repository.product.ShopDao;

@Component
@Transactional(readOnly = true)
public class ShopService {

    @Autowired
    private ShopDao shopDao;

    public static final long DEFAULT_SHOP_ID = 100;
    public static final long INVALID_SHOP_ID = -1;

    public Shop getShop(Long id) {
        return shopDao.findOne(id);
    }

    public Shop getShop(String id) {
        try {
            return getShop(Long.parseLong(id));
        } catch (Exception err) {
            return null;
        }
    }

    public Shop getShopByName(String name) {
        return shopDao.findByName(name);
    }

    public Shop getShopByDomainName(String domainName) {
        return shopDao.findByDomainName(domainName);
    }

    public Page<Shop> getMemberShop(Long memberId) {
        PageRequest pageRequest = new PageRequest(0, 100, new Sort(Direction.ASC, "name"));
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("memberUser.id", new SearchFilter("memberUser.id", Operator.EQ, memberId));
        Specification<Shop> spec = DynamicSpecifications.bySearchFilter(filters.values(), Shop.class);
        return shopDao.findAll(spec, pageRequest);
    }

    @Transactional(readOnly = false)
    public void saveShop(Shop shop) {
        shopDao.save(shop);
    }

    @Transactional(readOnly = false)
    public void deleteShop(Long id) {
        shopDao.changeStatus(id, Shop.STATUS_DELETED);
    }
}
